package org.tamal.jsf.bean;

import java.io.IOException;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.tamal.Constants;
import org.tamal.HttpSession;
import org.tamal.Util;
import org.tamal.persistence.User;

/**
 * This bean is responsible for log-in.
 * @author Tamal Kanti Nath
 */
@ManagedBean
public final class Login {

    private static final String REDIRECT_URL = "/";
    private static final String PASSWORD = "password";

    private String email;
    private String password;

    private FacesContext fc;
    private ExternalContext ext;
    private Map<String, Object> session;

    /**
     * Constructs login with a session.
     */
    public Login() {
        fc = FacesContext.getCurrentInstance();
        ext = fc.getExternalContext();
        session = ext.getSessionMap();
        session.remove(HttpSession.USER);
    }
    /**
     * Returns the email.
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets the email.
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * Returns the password.
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * Sets the password.
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * This method gets called on clicking on login button.
     * @throws IOException if unable to redirect
     */
    public void login() throws IOException {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        String msg = Util.getService().login(user);
        if (msg == null) {
            session.put(HttpSession.USER.name(), user);
            ext.redirect(REDIRECT_URL);
            return;
        }
        ResourceBundle rb = fc.getApplication()
                .getResourceBundle(fc, Constants.MSG);
        fc.addMessage(PASSWORD, new FacesMessage(rb.getString(msg)));
    }

}
